package com.yxjx.duoxue.payment;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Calendar;

import org.apache.http.client.ClientProtocolException;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.DatePicker;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.DatePicker.OnDateChangedListener;
import android.widget.TextView;

import com.yxjx.duoxue.BaseActionBarActivity;
import com.yxjx.duoxue.PageLoading;
import com.yxjx.duoxue.R;
import com.yxjx.duoxue.customview.MyProgressDialog;
import com.yxjx.duoxue.dao.Dao;
import com.yxjx.duoxue.datamodel.DMCourseCategory;
import com.yxjx.duoxue.datamodel.ResponseObject;
import com.yxjx.duoxue.global.Globals;
import com.yxjx.duoxue.mta.stat.StatHelper;
import com.yxjx.duoxue.my.UserRegActivity;
import com.yxjx.duoxue.network.MsgCode;
import com.yxjx.duoxue.network.UserLoginResponse;
import com.yxjx.duoxue.network.UserReg;
import com.yxjx.duoxue.payment.datamodel.DMKidInfo;
import com.yxjx.duoxue.payment.datamodel.DMKidInfoRefObject;
import com.yxjx.duoxue.utils.UIHelper;
import com.yxjx.duoxue.utils.Utils;

public class KidInfoEditActivity extends BaseActionBarActivity implements OnClickListener {
	
	public static final String KEY_KID_INFO_TOTAL = "KEY_KID_INFO_TOTAL";
	public static final String KEY_SHOW_SKIP_BTN = "KEY_SHOW_SKIP_BTN";
	private static final int REQ_CODE_PICK_COURSES = 2;
	
	private static final int REQ_CODE_PICK_LABELS = 1;
	private static final int MSG_LOAD_KID_LABELS_AND_COURSE_TYPES = 1;
	
	private TextView childBirthText;
	private TextView childCourseTypesText;
	private TextView childLabelsText;
	private ProgressDialog dialog;
	
	private DMKidInfoRefObject kidInfoTotal;
	private View scroller;
	
	private ArrayList<DMCourseCategory> selectedCourseTypes;
	private ArrayList<ConfigKidsDetailDTS> selectedLabels;
	private int selectedMonth = -1;
	private int selectedYear = -1;
	private String childName;
	private int childSex;
	private RadioGroup childSexView;
	private Context mContext;

	// 以后再说
	public void fillLater(View view) {
		StatHelper.addKVEvent(mContext, "event_kid_info_skip");
		finish();
	}

	public static String getCourseTypeIdString(ArrayList<DMCourseCategory> types) {
		if (types == null || types.size() == 0) {
			return "";
		}
		String ret = "";
		for (int i = 0; i < types.size() - 1; i++) {
			ret += (types.get(i).getType() + ",");
		}
		ret += (types.get(types.size() - 1).getType());
		return ret;
	}
	
	public static String getCourseTypesString(ArrayList<DMCourseCategory> types) {
		if (types == null || types.size() == 0) {
			return "";
		}
		String ret = "";
		for (int i = 0; i < types.size() - 1; i++) {
			ret += (types.get(i).getStr() + "，");
		}
		ret += (types.get(types.size() - 1).getStr());
		return ret;
	}
	
	public static String getLabelIdString(ArrayList<ConfigKidsDetailDTS> types) {
		if (types == null || types.size() == 0) {
			return "";
		}
		String ret = "";
		for (int i = 0; i < types.size() - 1; i++) {
			ret += (types.get(i).getId() + ",");
		}
		ret += (types.get(types.size() - 1).getId());
		return ret;
	}
	
	public static String getLabelsString(ArrayList<ConfigKidsDetailDTS> types) {
		if (types == null || types.size() == 0) {
			return "";
		}
		String ret = "";
		for (int i = 0; i < types.size() - 1; i++) {
			ret += (types.get(i).getKidsDes() + "，");
		}
		ret += (types.get(types.size() - 1).getKidsDes());
		return ret;
	}
	
	@Override
	protected void onActivityResult(int reqCode, int resultCode, Intent data) {
		if (reqCode == REQ_CODE_PICK_COURSES) {
			if (resultCode == RESULT_OK) {
				selectedCourseTypes = (ArrayList<DMCourseCategory>) data.getSerializableExtra(KidInfoSelectCoursesActivity.KEY_SELECT_COURSES);
				childCourseTypesText.setText(getCourseTypesString(selectedCourseTypes));
			}
		} else if (reqCode == REQ_CODE_PICK_LABELS) {
			if (resultCode == RESULT_OK) {
				selectedLabels = (ArrayList<ConfigKidsDetailDTS>) data.getSerializableExtra(KidInfoSelectLablesActivity.KEY_SELECT_LABELS);
				String labelsStr = getLabelsString(selectedLabels);
				childLabelsText.setText(labelsStr);
			}
		} else {
			super.onActivityResult(reqCode, resultCode, data);
		}
	}
	
	@Override
	public void onClick(final View arg0) {
		switch (arg0.getId()) {
		case R.id.pick_labels:
			pickLabels();
			break;
		case R.id.pick_date:
			OrderKidsConfigurationView.pickDate(this, selectedYear, selectedMonth, new OnDateChangedListener() {
				@Override
				public void onDateChanged(DatePicker picker, int year, int month, int day) {
					if (!isValidBirthDay(month, year)) {
						UIHelper.showTips(arg0, "请选择有效的年月");
						return;
					}
					selectedYear = year;
					selectedMonth = month + 1;
					setBirthText(selectedYear, selectedMonth);
				}
			});
			break;
		case R.id.pick_courses:
			pickCourses();
			break;
		}
	}
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.fragment_kid_info_edit);
		customizeActionBarTitle("学生信息");
		mContext = this;
		
		scroller = findViewById(R.id.scroller);
		UIHelper.setClickListener(scroller, R.id.pick_courses, this);
		UIHelper.setClickListener(scroller, R.id.pick_labels, this);
		UIHelper.setClickListener(scroller, R.id.pick_date, this);
		
		childBirthText = (TextView) scroller.findViewById(R.id.child_birth);
		childLabelsText = (TextView) scroller.findViewById(R.id.child_labels);
		childCourseTypesText = (TextView) scroller.findViewById(R.id.child_courses);
		childSexView = (RadioGroup) findViewById(R.id.child_sex);
		
		showLoading(true);
		
		new Thread(new Runnable() {
			
			@Override
			public void run() {
				// 尝试加载全部课程类别信息
				PageLoading.getCourseCategory(KidInfoEditActivity.this);
				// 尝试获取学生特点label全集
				JSONObject jo = new JSONObject();
				try {
					jo.put("date", System.currentTimeMillis());
					UserReg.getUserKids(jo, KidInfoEditActivity.this, true);
				} catch (JSONException e) {
					e.printStackTrace();
				} catch (UnsupportedEncodingException e) {
					e.printStackTrace();
				} catch (ClientProtocolException e) {
					e.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				} finally {
					mHandler.sendEmptyMessage(MSG_LOAD_KID_LABELS_AND_COURSE_TYPES);
				}
			}
		}).start();
		StatHelper.addKVEvent(mContext, "event_kid_info_open");

	}
	
	private Handler mHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case MSG_LOAD_KID_LABELS_AND_COURSE_TYPES:
				initData();
				showLoading(false);
				break;
			default:
				break;
			}
		};
	};
	private boolean showSkipButton;
	private boolean fromUserFirstLogin;
	
	

	private void initData() {
		// 初始化各个字段到value
		kidInfoTotal = (DMKidInfoRefObject) getIntent().getSerializableExtra(KEY_KID_INFO_TOTAL);
		if (kidInfoTotal != null) {
			selectedCourseTypes = kidInfoTotal.getSelectedCourseTypes();
			selectedLabels = kidInfoTotal.getSelectedLabels();
			selectedMonth = kidInfoTotal.getKidBIrthMonth();
			selectedYear = kidInfoTotal.getKidBirthYear();
			childSex = kidInfoTotal.getChildSex();
			childName = kidInfoTotal.getChildName();
			
			UIHelper.setText(scroller, R.id.child_name, childName);
			if (childSex == 1) {
				((RadioButton) childSexView.findViewById(R.id.child_sex_man)).setChecked(true);
			} else if (childSex == 2) {
				((RadioButton) childSexView.findViewById(R.id.child_sex_woman)).setChecked(true);
			} 
			childCourseTypesText.setText(getCourseTypesString(selectedCourseTypes));
			childLabelsText.setText(getLabelsString(selectedLabels));
			setBirthText(selectedYear, selectedMonth);
			
		}
		// 判断是否显示“以后再说”
		
		showSkipButton = showSkipButton();
		fromUserFirstLogin = getIntent().getBooleanExtra(KEY_SHOW_SKIP_BTN, false);
		findViewById(R.id.fillLater).setVisibility(showSkipButton ? View.VISIBLE : View.INVISIBLE);
		
	}

	private boolean showSkipButton() {
		Globals appDataModel = Globals.getInstance(this);
		boolean showSkipBtn = false;
		if (appDataModel != null && appDataModel.getKidOption() != null) {
			showSkipBtn = appDataModel.getKidOption().getAllowSkip() == 1;
		}
		return showSkipBtn;
	}
	
	private void pickCourses() {
		Intent intent = new Intent(this, KidInfoSelectCoursesActivity.class);
		intent.putExtra(KidInfoSelectCoursesActivity.KEY_SELECT_COURSES, selectedCourseTypes);
		startActivityForResult(intent, REQ_CODE_PICK_COURSES);
	}

	private void pickLabels() {
		Intent intent = new Intent(this, KidInfoSelectLablesActivity.class);
		intent.putExtra(KidInfoSelectLablesActivity.KEY_SELECT_LABELS, selectedLabels);
		startActivityForResult(intent, REQ_CODE_PICK_LABELS);
	}
	
	public void saveKidInfo(View view) {
		
		childName = UIHelper.getEditText(scroller, R.id.child_name);
		if (UIHelper.isEmpty(childName)) {
			UIHelper.showTips(scroller, "孩子的姓名不能为空");
			return;
		}
		
		childSex = 0;
		if (childSexView.getCheckedRadioButtonId() == R.id.child_sex_man) {
			childSex = 1;
		} else if (childSexView.getCheckedRadioButtonId() == R.id.child_sex_woman) {
			childSex = 2;
		} else {
			UIHelper.showTips(childLabelsText, "请选择孩子的性别");
			return;
		}
		
		if (selectedMonth <= 0|| selectedYear <= 0) {
			UIHelper.showTips(scroller, "请选择出生年月");
			return;
		}
		
//		if (selectedCourseTypes == null || selectedCourseTypes.size() == 0) {
//			UIHelper.showTips(scroller, "请选择期望课程类型");
//			return;
//		}
//		
//		if (selectedLabels == null || selectedLabels.size() == 0) {
//			UIHelper.showTips(scroller, "请选择性格特征");
//			return;
//		}
		
		final DMKidInfo kidInfo = new DMKidInfo();
		kidInfo.setCourseType(getCourseTypeIdString(selectedCourseTypes));
		kidInfo.setKidsBirthDay(1);
		kidInfo.setKidsBirthMonth(selectedMonth);
		kidInfo.setKidsBirthYear(selectedYear);
		kidInfo.setKidsDetail(getLabelIdString(selectedLabels));
		kidInfo.setKidsName(childName);
		kidInfo.setKidsSex(childSex);
		kidInfo.setTime(System.currentTimeMillis());
		
		
		final JSONObject jo = kidInfo.getJsonObject();
		dialog = MyProgressDialog.show(KidInfoEditActivity.this, "", "正在保存学生信息");
		
		kidInfoTotal = new DMKidInfoRefObject();
		kidInfoTotal.setChildName(childName);
		kidInfoTotal.setChildSex(childSex);
		kidInfoTotal.setKidBIrthMonth(selectedMonth);
		kidInfoTotal.setKidBirthYear(selectedYear);
		kidInfoTotal.setSelectedCourseTypes(selectedCourseTypes);
		kidInfoTotal.setSelectedLabels(selectedLabels);
		
		Thread thread = new Thread(new Runnable() {
			@Override
			public void run() {
				try {
					ResponseObject rspObj = UserReg.saveKidInfo(jo, KidInfoEditActivity.this);
					if (rspObj.isOk()) {
						UIHelper.showTips(scroller, "保存成功");
						Dao.setUserKidInfo(KidInfoEditActivity.this, ClientUserKidsDTS.from(kidInfo.toString()));
						StatHelper.addKVEvent(mContext, "event_kid_info_save");
						Intent intent = new Intent();
						intent.putExtra(KEY_KID_INFO_TOTAL, kidInfoTotal);
						setResult(RESULT_OK, intent);
						finish();
					} else {
						UIHelper.showTips(scroller, MsgCode.descFor(rspObj));
					}
				} catch (UnsupportedEncodingException e) {
					e.printStackTrace();
				} catch (ClientProtocolException e) {
					e.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				} catch (JSONException e) {
					e.printStackTrace();
				} finally {
					if (dialog != null) {
						dialog.dismiss();
					}
				}
			}
		});
		thread.start();
	}

	private void setBirthText(int year, int month) {
		if (year < 0 || month < 0) {
			childBirthText.setText("－");
			return;
		}
		String birthText = "" + year + "-" + (month);
		childBirthText.setText(birthText);
	}
	
	private void showLoading(final boolean showing) {
		findViewById(R.id.loading).setVisibility(showing ? View.VISIBLE : View.INVISIBLE);
		findViewById(R.id.root).setVisibility(showing ? View.INVISIBLE : View.VISIBLE);
	}
	
	private boolean isValidBirthDay(int month, int year) {
		Calendar cal = Calendar.getInstance();
		int nowMonthCount = cal.get(Calendar.YEAR) * 12 + cal.get(Calendar.MONTH);
		int selectedMonthCount = month + year * 12;
		return selectedMonthCount <= nowMonthCount;
	}
	
	@Override
	public void onBackPressed() {
		if (!showSkipButton && fromUserFirstLogin) {
			return;
		}
		super.onBackPressed();
	}
	
}
